<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\model\BehaviorCategory;
use app\common\model\BehaviorRecord;
use app\common\model\Category as CategoryModel;
use app\common\model\Config;
use fast\Tree;
use think\Db;
use think\Exception;
use think\exception\PDOException;

/**
 * 图片库
 *
 */
class Album extends Backend
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];
    protected $schoolLimit = true;

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 查看
     */
    public function index()
    {
        return $this->view->fetch();
    }

    public function data()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $type = $this->request->request('type');
            switch ($type) {
                case 'dorm':
                    $key = 'dorm_id';
                    $behavior_category_type = [BehaviorCategory::DORM, BehaviorCategory::DORM_STUDENT];
                    break;
                case 'classes':
                    $key = 'class_id';
                    $behavior_category_type = [BehaviorCategory::CLASSES];
                    break;
                case 'student':
                    $key = 'student_id';
                    $behavior_category_type = [BehaviorCategory::STUDENT];
                    break;
            }

            if (!isset($key)) {
                return json(array("total" => 0, "rows" => []));
            }

            $total = BehaviorRecord::alias('record')
                ->join('__BEHAVIOR_RECORD_IMAGE__ image', 'image.record_id = record.id')
                ->where($where)
                ->where('record.' . $key, '>', 0)
                ->whereIn('record.behavior_category_type', $behavior_category_type)
                ->group('record.' . $key)
                ->count();

            $list = BehaviorRecord::alias('record')
                ->join('__BEHAVIOR_RECORD_DETAIL__ detail', 'detail.record_id = record.id')
                ->join('__BEHAVIOR_RECORD_IMAGE__ image', 'image.record_id = record.id')
                ->where($where)
                ->where("record.$key", '>', 0)
                ->whereIn('record.behavior_category_type', $behavior_category_type)
                ->field("record.$key id,record.$key,record.json_data,sum(detail.score) score,count(image.id) image_count")
                ->group("record.$key")
                ->order("record.$key", 'asc')
                ->limit($offset, $limit)
                ->select();

            if ($list) {
                switch ($type) {
                    case 'dorm':
                        $dorm_ids = array_column(collection($list)->toArray(), 'dorm_id');
                        $client = new \app\common\library\Client(config('dorm.url'));
                        $dorms = $client->dormProfile($dorm_ids);
                        foreach ($list as $key => $value) {
                            if ($value['json_data']) {
                                $list[$key]['school_name'] = @$value['json_data']['school_name'];
                                $list[$key]['garden_name'] = $value['json_data']['garden_name'];
                                $list[$key]['building_name'] = $value['json_data']['building_name'];
                                $list[$key]['dorm_number'] = $value['json_data']['dorm_number'];
                            }

                            if (isset($dorms[$value['dorm_id']])) {
                                $list[$key]['dorm_floor'] = $dorms[$value['dorm_id']]['floor'];
                                $list[$key]['dorm_used_count'] = $dorms[$value['dorm_id']]['bed_used_count'];
                            }
                        }
                        break;
                    case 'classes':
                        $class_ids = array_column($list, 'class_id');
                        $classes = \app\common\library\Client::instance()->classesProfile($class_ids);

                        foreach ($list as $key => $value) {
                            if (isset($classes[$value['class_id']])) {
                                $list[$key]['school_name'] = $classes[$value['class_id']]['school_name'];
                                $list[$key]['grade_name'] = $classes[$value['class_id']]['grade_name'];
                                $list[$key]['class_name'] = $classes[$value['class_id']]['name'];
                                $list[$key]['headmaster_name'] = $classes[$value['class_id']]['headmaster_name'];
                            }
                        }
                        break;
                    case 'student':
                        $student_ids = array_column(collection($list)->toArray(), 'student_id');
                        $students = \app\common\library\Client::instance()->studentProfile($student_ids);

                        foreach ($list as $key => $value) {
                            if ($value['json_data']) {
                                $list[$key]['school_name'] = @$value['json_data']['school_name'];
                                $list[$key]['class_name'] = $value['json_data']['class_name'];
                                $list[$key]['name'] = $value['json_data']['student_name'];
                            }
                            if (isset($students[$value['student_id']])) {
                                $list[$key]['school_name'] = $students[$value['student_id']]['school_name'];
                                $list[$key]['name'] = $students[$value['student_id']]['name'];
                                $list[$key]['gender_text'] = $students[$value['student_id']]['gender_text'];
                            }
                        }
                        break;
                }
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch('index');
    }

//    // 宿管
//    public function dorm()
//    {
//        //设置过滤方法
//        $this->request->filter(['strip_tags']);
//        if ($this->request->isAjax()) {
//            //如果发送的来源是Selectpage，则转发到Selectpage
//            if ($this->request->request('keyField')) {
//                return $this->selectpage();
//            }
//
//            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
//
//            $total = BehaviorRecord::alias('record')
//                ->join('__BEHAVIOR_RECORD_IMAGE__ image', 'image.record_id = record.id')
//                ->where($where)
//                ->where('record.dorm_id', '>', 0)
//                ->whereIn('record.behavior_category_type', [BehaviorCategory::DORM, BehaviorCategory::DORM_STUDENT])
//                ->group('record.dorm_id')
//                ->count();
//
//            $list = BehaviorRecord::alias('record')
//                ->join('__BEHAVIOR_RECORD_DETAIL__ detail', 'detail.record_id = record.id')
//                ->join('__BEHAVIOR_RECORD_IMAGE__ image', 'image.record_id = record.id')
//                ->where($where)
//                ->where('record.dorm_id', '>', 0)
//                ->whereIn('record.behavior_category_type', [BehaviorCategory::DORM, BehaviorCategory::DORM_STUDENT])
//                ->field('record.dorm_id,record.json_data,sum(detail.score) score,count(image.id)')
//                ->group('record.dorm_id')
//                ->order('record.dorm_id', 'asc')
//                ->limit($offset, $limit)
//                ->select();
//
//            if ($list) {
//                $dorm_ids = array_column(collection($list)->toArray(), 'dorm_id');
//                $client = new \app\common\library\Client(config('dorm.url'));
//                $dorms = $client->dormProfile($dorm_ids);
//                foreach ($list as $key => $value) {
//                    if ($value['json_data']) {
//                        $list[$key]['school_name'] = @$value['json_data']['school_name'];
//                        $list[$key]['garden_name'] = $value['json_data']['garden_name'];
//                        $list[$key]['building_name'] = $value['json_data']['building_name'];
//                        $list[$key]['dorm_number'] = $value['json_data']['dorm_number'];
//                    }
//
//                    if (isset($dorms[$value['dorm_id']])) {
//                        $list[$key]['dorm_floor'] = $dorms[$value['dorm_id']]['floor'];
//                        $list[$key]['dorm_used_count'] = $dorms[$value['dorm_id']]['bed_used_count'];
//                    }
//                }
//            }
//
//            $result = array("total" => $total, "rows" => $list);
//
//            return json($result);
//        }
//        return $this->view->fetch('index');
//    }
//
//    // 班级
//    public function classes()
//    {
//        //设置过滤方法
//        $this->request->filter(['strip_tags']);
//        if ($this->request->isAjax()) {
//            //如果发送的来源是Selectpage，则转发到Selectpage
//            if ($this->request->request('keyField')) {
//                return $this->selectpage();
//            }
//
//            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
//
//            $total = BehaviorRecord::alias('record')
//                ->join('__BEHAVIOR_RECORD_IMAGE__ image', 'image.record_id = record.id')
//                ->where($where)
//                ->where('record.class_id', '>', 0)
//                ->where('record.behavior_category_type', BehaviorCategory::CLASSES)
//                ->group('record.class_id')
//                ->count();
//
//            $list = BehaviorRecord::alias('record')
//                ->join('__BEHAVIOR_RECORD_DETAIL__ detail', 'detail.record_id = record.id')
//                ->join('__BEHAVIOR_RECORD_IMAGE__ image', 'image.record_id = record.id')
//                ->where($where)
//                ->where('record.class_id', '>', 0)
//                ->where('record.behavior_category_type', BehaviorCategory::CLASSES)
//                ->field('record.class_id id,record.class_id,record.json_data,sum(detail.score) score,count(image.id) image_count')
//                ->group('record.class_id')
//                ->order('record.class_id', 'asc')
//                ->limit($offset, $limit)
//                ->select();
//
//            if ($list) {
//                $class_ids = array_column($list, 'class_id');
//                $classes = \app\common\library\Client::instance()->classesProfile($class_ids);
//
//                foreach ($list as $key => $value) {
//                    if (isset($classes[$value['class_id']])) {
//                        $list[$key]['school_name'] = $classes[$value['class_id']]['school_name'];
//                        $list[$key]['grade_name'] = $classes[$value['class_id']]['grade_name'];
//                        $list[$key]['class_name'] = $classes[$value['class_id']]['name'];
//                        $list[$key]['headmaster_name'] = $classes[$value['class_id']]['headmaster_name'];
//                    }
//                }
//            }
//
//            $result = array("total" => $total, "rows" => $list);
//
//            return json($result);
//        }
//        return $this->view->fetch('index');
//    }
//
//    // 学生
//    public function student()
//    {
//        //设置过滤方法
//        $this->request->filter(['strip_tags']);
//        if ($this->request->isAjax()) {
//            //如果发送的来源是Selectpage，则转发到Selectpage
//            if ($this->request->request('keyField')) {
//                return $this->selectpage();
//            }
//
//            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
//
//            $total = BehaviorRecord::alias('record')
//                ->join('__BEHAVIOR_RECORD_IMAGE__ image', 'image.record_id = record.id')
//                ->where($where)
//                ->where('record.student_id', '>', 0)
//                ->where('record.behavior_category_type', BehaviorCategory::STUDENT)
//                ->group('record.student_id')
//                ->count();
//
//            $list = BehaviorRecord::alias('record')
//                ->join('__BEHAVIOR_RECORD_DETAIL__ detail', 'detail.record_id = record.id')
//                ->join('__BEHAVIOR_RECORD_IMAGE__ image', 'image.record_id = record.id')
//                ->where($where)
//                ->where('record.student_id', '>', 0)
//                ->where('record.behavior_category_type', BehaviorCategory::STUDENT)
//                ->field('record.student_id,record.json_data,sum(detail.score) score,count(image.id) image_count')
//                ->group('record.student_id')
//                ->order('record.student_id', 'asc')
//                ->limit($offset, $limit)
//                ->select();
//
//            if ($list) {
//                $student_ids = array_column(collection($list)->toArray(), 'student_id');
//                $students = \app\common\library\Client::instance()->studentProfile($student_ids);
//
//                foreach ($list as $key => $value) {
//                    if ($value['json_data']) {
//                        $list[$key]['school_name'] = @$value['json_data']['school_name'];
//                        $list[$key]['class_name'] = $value['json_data']['class_name'];
//                        $list[$key]['name'] = $value['json_data']['student_name'];
//                    }
//                    if (isset($students[$value['student_id']])) {
//                        $list[$key]['school_name'] = $students[$value['student_id']]['school_name'];
//                        $list[$key]['name'] = $students[$value['student_id']]['name'];
//                        $list[$key]['gender_text'] = $students[$value['student_id']]['gender_text'];
//                    }
//                }
//            }
//
//            $result = array("total" => $total, "rows" => $list);
//
//            return json($result);
//        }
//        return $this->view->fetch('index');
//    }

    // 详细信息
    public function detail()
    {
        $id = $this->request->request('ids');
        $type = $this->request->request('type');

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {

            $key = '';
            $behavior_category_type = [];
            switch ($type) {
                case 'dorm':
                    $key = 'dorm_id';
                    $behavior_category_type = [BehaviorCategory::DORM, BehaviorCategory::DORM_STUDENT];
                    break;
                case 'classes':
                    $key = 'class_id';
                    $behavior_category_type = [BehaviorCategory::CLASSES];
                    break;
                case 'student':
                    $key = 'student_id';
                    $behavior_category_type = [BehaviorCategory::STUDENT];
                    break;
            }

            if (!$key) {
                return json(["total" => 0, "rows" => []]);
            }

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = BehaviorRecord::alias('record')
                ->join('__BEHAVIOR_RECORD_IMAGE__ image', 'image.record_id = record.id')
                ->where('record.' . $key, $id)
                ->whereIn('record.behavior_category_type', $behavior_category_type)
                ->where($where)
                ->count();

            $list = BehaviorRecord::alias('record')
                ->join('__BEHAVIOR_RECORD_IMAGE__ image', 'image.record_id = record.id', 'right')
                ->where('record.' . $key, $id)
                ->whereIn('record.behavior_category_type', $behavior_category_type)
                ->where($where)
                ->field("image.id,record.behavior_category_type,record.record_user_id,record.record_user_group,record.created_at,record.json_data,image.url,'$type' type")
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            return json(["total" => $total, "rows" => $list]);
        }
        $this->assignconfig("admin", ['ids' => $id, 'type' => $type]);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {

            $this->model = model('BehaviorRecordImage');
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $schoolIds = $this->getDataLimitSchoolIds();
            if (is_array($schoolIds)) {
                $this->model->where($this->schoolLimitField, 'in', $schoolIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}
